package com.zym.init.service.impl;

import com.zym.init.core.auth.service.TokenService;
import com.zym.init.core.exception.ServiceException;
import com.zym.init.model.bo.LoginUser;
import com.zym.init.service.LoginService;
import com.zym.init.service.UserService;
import com.zym.init.core.utils.SecurityUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {


    private final AuthenticationManager authenticationManager;
    private final UserService userService;
    private final TokenService tokenService;

    public LoginServiceImpl(AuthenticationManager authenticationManager, UserService userService, TokenService tokenService) {
        this.authenticationManager = authenticationManager;
        this.userService = userService;
        this.tokenService = tokenService;
    }

    /**
     * 用户名密码登录
     *
     * @param username 用户名
     * @param password 密码
     * @return token
     */
    @Override
    public String login(String username, String password) {
        try {
            // 获取用户名密码并封装为请求Authentication
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            // 认证管理器进行认证（账号密码比对） 认证完成后认证管理器返回用户信息
            Authentication authenticate = authenticationManager.authenticate(authenticationToken);
            if (Objects.isNull(authenticate)) {
                throw new ServiceException("登录失败");
            }
            // 获取用户信息
            LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
            // 检查账号是否已被封禁
            userService.checkUserIsBanned(loginUser.getUserId());
            // 生成token
            return tokenService.createToken(loginUser);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new ServiceException("用户名或密码错误");
            } else {
                throw new ServiceException(e.getMessage());
            }
        }
    }

    /**
     * 注销当前登录用户的token
     */
    @Override
    public void logout() {
        tokenService.delLoginUser(SecurityUtils.getLoginUser().getToken());
    }

}
